/*
#	Fastfoo - CMS developer under CakePHP / http://fast-foo.com
#	Copyright (C) 2010  Antonio Irlandés García

#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.

#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.

#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


/*
** Funciones para el tratamiento de los datos via AJAX
*/

//Envia los datos del formulario, devolviendo un mensaje y actualizando capas
function ajaxFormUpdater(form, updater, loading){

	new Ajax.Updater(updater,
					$(form).readAttribute('action'), 
					{	asynchronous:true,
						evalScripts:true, 
						parameters:Form.serialize(form), 
						requestHeaders:['X-Update', updater],
						onComplete:function(request, json) {
										$(form).reset();
										Element.hide(loading);
										//Reseteamos los valores del formulario
									}, 
						onLoading:function(request){
										Element.show(loading);
									},
						onSuccess:function(transport) {
										$(form).reset();
										//Reseteamos los valores del formulario
									}
					}
	);


}

//Envia los datos del formulario, validando la entrada de datos, devolviendo un mensaje
function ajaxFormRequest(form, loading){

	new Ajax.Request($(form).readAttribute('action'), 
					{	asynchronous:true,
						evalScripts:true, 
						parameters:Form.serialize(form),
						onComplete:function(request, json) {
										Element.hide(loading);
									}, 
						onLoading:function(request){
										Element.show(loading);
									}, 
						onSuccess: function(transport){
										//ARRAY(hash) --> JSON --> OBJECT
										eval("object_json = " + transport.responseText.toJSON().evalJSON());

										//Si todo salio bien y pulso en publicar redirijo al listado(por regla general)
										if(object_json.result_action && object_json.url_redirect != null){
											window.location = object_json.url_redirect;
										}else{
											//Cambio valor de campo oculto de identificador por si se desea guardar
											//mientras se esta editando y esto no genere un registro nuevo
											if (object_json.result_action && object_json.value_reg != null)
												setId(object_json.name_reg, object_json.value_reg);
											//Muestro mensaje
											//showMessage('message_system', object_json.msg_result, object_json.msg_class);
											createMessage(object_json.msg_result, 'main');

										}
									}
						
					}
	);

}

//Activa un usuario
function ajaxSetActive(id, active, url, loading){
	new Ajax.Request(url, 
					{	method: 'post',
						parameters:{ id: id, active: active },
						asynchronous:true,
						evalScripts:true, 
						onComplete:function(request, json) {
										Element.hide(loading);
									}, 
						onLoading:function(request){
										Element.show(loading);
									}
						
					}
	);

}

//Publica una pagina o post
function ajaxSetPublic(id, estate, url, loading){
	new Ajax.Request(url, 
					{	method: 'post',
						parameters:{ id: id, estate: estate },
						asynchronous:true,
						evalScripts:true, 
						onComplete:function(request, json) {
										Element.hide(loading);
									}, 
						onLoading:function(request){
										Element.show(loading);
									}
						
					}
	);

}

//Comprueba la fuerza de una clave
function ajaxGetPasswordStrength(field, capa, url){
	
	new Ajax.Request(url,
								{ method: 'post'
								 ,parameters:{ password: $(field).value }
								 ,onSuccess: function(transport){
											//ARRAY(hash) --> JSON --> OBJECT
											eval("object_json = " + transport.responseText.toJSON().evalJSON());

											switch (object_json.strength){
			
												case 0:
												case 1:
												case 2:
												  style = "bad_pass";
												break;

												case 3:
												case 4:
												  style = "good_pass";
												break;

												case 5:
												case 6:
												case 7:
												case 8:
												  style = "strong_pass";
												break;

												default:
													style = "strong_pass";
		
											}

											//Pasamos valores a la capa
											setInfoDiv(capa, style, object_json.strength_msg);

											//Muestro la capa
											if($(capa).readAttribute('style') == "display: none;")
												Effect.toggle(capa);
								}


							}
	);
}

//Actualiza el contenido de esta y su clase
function setInfoDiv(capa, style,text){
	//texto
	$(capa).update(text);

	//cambio los estilos
	if(style != null && !$(capa).hasClassName(style)){
		$(capa).removeClassName($(capa).classNames());
		$(capa).addClassName(style);
	}

}


//Encargada de actualizar el campo id del formulario
function setId(field, value){
	$(field).value = value; 
}

//Encargada de crear las capas del mensaje del sistema en la confirmación de los formularios
function createMessage(text, parent_div){

	//Compruebo que la capa no esta creada ya
	if(!$('flashMessage')){

		//Capa padre
		var attrs_parent = {
			id : 'flashMessage',
			style: 'display:none;'
		}; 
		var div_message = new Element('div', attrs_parent);

		div_message.update(text);//texto

		//Coloco a las capas dentro de la estructura del DOM 
	  	$(parent_div).insert({ top : div_message});

		//Mostramos mensajes			
		showMessage('flashMessage');

	}else{
		$('flashMessage').update(text);//texto
	}	
	
		
}

//Encargada de mostrar el mensaje de sistema
function showMessage(show){

	//Lo muestro
	Effect.toggle(show,'appear',
					{delay: 0
					 ,afterFinish: function(){
									//Lo oculto
									Effect.toggle(show, 'appear', { delay: 5.0 ,
																	afterFinish: function(){
																					//Lo elimino
																					$(show).remove();
																				}
																}
												);

								}
					}
				);
	
}
